package net.haier.fashion.trend.report.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.haier.fashion.trend.report.core.exception.ServiceException;

import java.util.List;

public class JsonUtil {

    private JsonUtil() {
    }

    private static final ObjectMapper mapper = new ObjectMapper();

    static {
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    /**
     * 将对象转换为json字符串
     *
     * @param obj
     * @return
     * @throws Exception
     */
    public static String obj2string(Object obj) {
        if (obj == null) {
            return "";
        }
        try {
            return mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new ServiceException("序列化时出错:", e);
        }
    }

    /**
     * 将字符串转为对象
     *
     * @param <T>
     * @param jsonStr
     * @param cls
     * @return
     */
    public static <T> T str2obj(String jsonStr, Class<T> cls) {
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        T obj = null;
        if (jsonStr != null && jsonStr.length() > 1) {
            try {
                obj = mapper.readValue(jsonStr, cls);
            } catch (Exception e) {
                throw new ServiceException("反序列化时出错:", e);
            }
        }
        return obj;
    }

    public static <T> List<T> str2list(String jsonStr, Class<T> cls) {
        List<T> objList = null;
        try {
            JavaType t = mapper.getTypeFactory().constructParametricType(List.class, new Class[]{cls});
            objList = (List)mapper.readValue(jsonStr, t);
            return objList;
        } catch (Exception var4) {
            Exception e = var4;
            throw new RuntimeException("反序列化为List对象时出错:", e);
        }
    }


}
